package com.example.allshengmedical.experimentnew.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.allsheng.widget.AllShengDialog;
import com.allsheng.widget.AllShengDialog.ClickListenerInterface;
import com.example.allshengmedical.R;
import com.example.allshengmedical.base.BaseActivity;
import com.example.allshengmedical.base.BaseApplication;
import com.example.allshengmedical.experimentnew.activity.FileManagerActivity.FolderAdapter;
import com.example.allshengmedical.experimentnew.activity.FileManagerActivity.FolderAdapter.ViewHolder;
import com.example.allshengmedical.experimentnew.bean.FileBean;
import com.example.allshengmedical.experimentnew.bean.FolderBean;
import com.example.allshengmedical.experimentnew.presenter.FileManagerPresenter;
import com.example.allshengmedical.experimentnew.view.IFileManagerView;
import com.example.allshengmedical.experimentrun.activity.BrowseActivity;
import com.example.allshengmedical.experimentrun.activity.BrowseActivity.FileAdapter;
import com.example.allshengmedical.mainmenu.activity.MainMenuActivity;
import com.example.allshengmedical.util.ByAlert;
import com.example.allshengmedical.util.CopyFile;
import com.example.allshengmedical.util.FileManagerUtil;
import com.example.allshengmedical.util.LogUtil;
import com.example.allshengmedical.util.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

//新版本的文件管理界面
public class ManagerActivity1 extends BaseActivity implements IFileManagerView, OnClickListener {

	private FileManagerPresenter fileManagerPresenter;
	private LinearLayout little_layout;
	private TextView newTv, editTv, copyTv, delTv, stateTv, fileNameTV, editFolderBtn, editFileBtn;

	private ListView folderList, fileList;
	private FileManagerUtil fileManagerUtil;

	private FolderAdapter folderAdapter;
	private Boolean folderSelector = true;

	private FileAdapter fileAdapter;

	AllShengDialog allShengDialog;
	private List<FileBean> fileBeans2;

	Button bottomLeftFistBtn, bottomCenterBtn, bottomRightBtn;

	// 数据
	String folderName;
	String fileName;
	private String appFilePath = Environment.getExternalStorageDirectory() + "/" + "AllShengMedical";

	@Override
	protected int setcontent() {
		return R.layout.activity_new_filemanager1;
	}

	@Override
	protected void initView() {
		fileManagerPresenter = new FileManagerPresenter(this);

		fileManagerUtil = new FileManagerUtil();
		fileManagerPresenter.initAppHead();
		fileManagerPresenter.initBottomView();

		fileManagerUtil.createDefault();

		initFolderListView();
		initFileListView();

	}

	private void initFileListView() {
		// fileBean = new FileBean("", "Date Time");

		// 读取
		SharedPreferences preferences = getSharedPreferences(BaseApplication.FILEMANGER_HISTORYARRAYLIST, MODE_PRIVATE);
		String json = preferences.getString("fileBean", null);
		fileBeans2 = new ArrayList<FileBean>();
		if (json != null) {
			Gson gson = new Gson();
			Type type = new TypeToken<List<FileBean>>() {
			}.getType();

			fileBeans2 = gson.fromJson(json, type);
			for (int i = 0; i < fileBeans2.size(); i++) {
				Log.d("读sp", fileBeans2.get(i).getFoldName() + ":" + fileBeans2.get(i).getFileName() + ","
						+ fileBeans2.get(i).getCreateTime());
			}
		}

		fileAdapter = new FileAdapter(ManagerActivity1.this, (ArrayList<FileBean>) fileBeans2);
		fileList.setAdapter(fileAdapter);

		fileList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

				for (FileBean bean : fileBeans2) {
					bean.setIsSelected("");
				}
				fileBeans2.get(position).setIsSelected("true");
				fileAdapter.notifyDataSetChanged();
			}
		});

		delTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				Boolean selectBoolean = false;
				for (FileBean bean : fileBeans2) {
					if (!TextUtils.isEmpty(bean.getIsSelected())) {
						selectBoolean = true;

					}
				}
				if (!selectBoolean) {
					allShengDialog = new AllShengDialog(ManagerActivity1.this, "", "选中后才能删除！", "确定");
					allShengDialog.setClicklistener(new AllShengDialog.ClickListenerInterface() {

						@Override
						public void Cancle() {
							allShengDialog.dismiss();

						}

						@Override
						public void OK() {
							allShengDialog.dismiss();

						}

					});
					allShengDialog.show();
					return;
				}
				allShengDialog = new AllShengDialog(ManagerActivity1.this, "", "确认删除么！", "确定", "取消");
				allShengDialog.setClicklistener(new AllShengDialog.ClickListenerInterface() {

					@Override
					public void OK() {

						for (FileBean bean : fileBeans2) {
							if (!TextUtils.isEmpty(bean.getIsSelected())) {
								fileBeans2.remove(bean);
								// fileManagerUtil.delFIle(bean.getFoldName(),
								// bean.getFileName());
								folderName = bean.getFoldName();
								fileName = bean.getFileName();

								String path = appFilePath + "/" + folderName;

								File file = new File(path + "/" + fileName);
								if (file.isFile() && file.exists()) {// 路径为文件且不为空则进行删除
									file.delete();// 文件删除

								}
								break;

							}
						}

						// 写回sp
						// 写
						SharedPreferences.Editor editor = getSharedPreferences(
								BaseApplication.FILEMANGER_HISTORYARRAYLIST, MODE_PRIVATE).edit();
						Gson gson = new Gson();
						String json2 = gson.toJson(fileBeans2);
						Log.d("gson写", "saved json is " + json2);
						editor.putString("fileBean", json2);
						editor.commit();

						fileAdapter.notifyDataSetChanged();
						allShengDialog.dismiss();
					}

					@Override
					public void Cancle() {
						// TODO Auto-generated method stub
						allShengDialog.dismiss();
					}

				});

				allShengDialog.show();

			}
		});

		editTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Boolean selectBoolean = false;
				for (FileBean bean : fileBeans2) {
					if (!TextUtils.isEmpty(bean.getIsSelected())) {
						selectBoolean = true;

					}
				}
				if (!selectBoolean) {
					allShengDialog = new AllShengDialog(ManagerActivity1.this, "", "需要选中文件后再进行修改！", "确定");
					allShengDialog.setClicklistener(new AllShengDialog.ClickListenerInterface() {

						@Override
						public void Cancle() {
							allShengDialog.dismiss();

						}

						@Override
						public void OK() {
							allShengDialog.dismiss();

						}

					});
					allShengDialog.show();
					return;
				}

				folderName = SharedPreferencesUtils.get(ManagerActivity1.this,
						BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "") + "";
				fileName = SharedPreferencesUtils.get(ManagerActivity1.this, BaseApplication.FILEMANGER_PREPAREFILENAME,
						"") + "";

				String path = appFilePath + "/" + folderName;

				File file = new File(path + "/" + fileName);
				BufferedReader reader = null;
				StringBuffer contextString = new StringBuffer();
				try {
					System.out.println("以行为单位读取文件内容，一次读一整行:");
					reader = new BufferedReader(new FileReader(file));
					String tempString = null;
					int line = 1;
					// 一次读入一行，直到读入null为文件结束
					while ((tempString = reader.readLine()) != null) {
						// 显示行号
						// System.out.println("line " + line + ": " +
						// tempString);
						// Log.e("--", tempString);
						contextString.append(tempString);
						contextString.append(",");
						line++;
					}
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (reader != null) {
						try {
							reader.close();
							// LogUtil.e("!!", contextString + "");

						} catch (IOException e1) {
						}
					}
				}
				// LogUtil.e(contextString);
				if (!contextString.toString().contains("Aisle")) {
					ByAlert.alert(getString(R.string.ana_brow_layout1_));
					return;
				}
				if (!contextString.toString().contains("dataSourceListBlock1")
						| !contextString.toString().contains("dataSourceListBlock2")) {
					ByAlert.alert(getString(R.string.ana_brow_genepan));
					return;
				}
				if (!contextString.toString().contains("Methods")) {
					ByAlert.alert(getString(R.string.ana_brow_methods_));
					return;
				}
				if (contextString.toString().contains(",,Channel1")) {
					// 在分析数据的时候应该将判断条件前面加非
					ByAlert.alert(getString(R.string.runpreview_havedata));
					return;
				}

				// 先将本页面的存储的信息暂时保存到sp中

				for (int i = 0; i < fileBeans2.size(); i++) {
					// folderNames.get(i).getIsSelected();
					if (!TextUtils.isEmpty(fileBeans2.get(i).getIsSelected())) {
						SharedPreferencesUtils.put(ManagerActivity1.this, BaseApplication.FILEMANGER_PREPAREFOLDERPATH,
								fileBeans2.get(i).getFoldName());

						SharedPreferencesUtils.put(ManagerActivity1.this, BaseApplication.FILEMANGER_PREPAREFILENAME,
								fileBeans2.get(i).getFileName());
					}

				}
				// 把重名的效果去掉
				// if (!fileManagerUtil.fileExist((String)
				// SharedPreferencesUtils
				// .get(ManagerActivity1.this,
				// BaseApplication.FILEMANGER_PREPAREFOLDERPATH,
				// "0"), (String) SharedPreferencesUtils.get(
				// ManagerActivity1.this,
				// BaseApplication.FILEMANGER_PREPAREFILENAME, "0"),
				// ManagerActivity1.this)) {
				// // final AllShengDialog allShengDialog = new AllShengDialog(
				// // BaseApplication.getContext(), "",
				// // "此文件已经创建过，请更换文件名称", "OK");
				// // allShengDialog
				// // .setClicklistener(new ClickListenerInterface() {
				// //
				// // @Override
				// // public void OK() {
				// // // TODO Auto-generated method stub
				// // allShengDialog.dismiss();
				// // }
				// //
				// // });
				// // allShengDialog.show();
				// return;
				// }

				allShengDialog = new AllShengDialog(ManagerActivity1.this, "",
						"你要编辑文件路径是:"
								+ (String) SharedPreferencesUtils.get(ManagerActivity1.this,
										BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0")
								+ "\n你选择的文件名称是:" + (String) SharedPreferencesUtils.get(ManagerActivity1.this,
										BaseApplication.FILEMANGER_PREPAREFILENAME, "0"),
						"确定");
				allShengDialog.setClicklistener(new AllShengDialog.ClickListenerInterface() {

					@Override
					public void OK() {
						// TODO Auto-generated method stub
						Intent nextIntent = new Intent(ManagerActivity1.this, EditBaseInformationActivity.class);

						startActivity(nextIntent);
						allShengDialog.dismiss();
					}

					@Override
					public void Cancle() {
						// TODO Auto-generated method stub
						allShengDialog.dismiss();
					}

				});
				allShengDialog.show();
			}
		});
	}

	@Override
	protected void initData() {
		StringBuffer fileName = new StringBuffer();
		if (TextUtils.isEmpty(fileNameTV.getText())) {
			fileName.append("File");
			SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
			fileName.append(myFmt.format(System.currentTimeMillis()));

		}
		fileNameTV.setText(fileName + "");

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.newTv:
			little_layout.setVisibility(View.VISIBLE);
			stateTv.setText(R.string.filestate_new);
			bottomRightBtn.setVisibility(View.VISIBLE);
			break;
		case R.id.editTv:

			break;
		case R.id.copyTv:
			little_layout.setVisibility(View.VISIBLE);
			stateTv.setText(R.string.filestate_saveas);
			bottomRightBtn.setVisibility(View.VISIBLE);
			break;
		case R.id.delTv:
			// 删除弹警告框
			break;

		case R.id.editFileBtn:
			fileManagerPresenter.editFileFunction();
			break;
		case R.id.editFolderBtn:
			fileManagerPresenter.editFolderFunction();
			break;
		case R.id.fileNameTV:
			fileManagerPresenter.editFileFunction();
			break;
		default:
			break;
		}

	}

	@Override
	public void initAppHead() {
		setActionBar();
		setSystemTime();

	}

	@Override
	public void initBottomView() {
		setBottomView();

	}

	@Override
	public void searchFunction() {
		// TODO Auto-generated method stub

	}

	@Override
	public void editFolderFunction() {

		if (folderSelector) {
			for (int i = 0; i < folderList.getCount() - 1; i++) {

				if (!TextUtils.isEmpty(fileManagerUtil.getFolderNames().get(i).getIsSelected())) {

					if ("Default".equals(fileManagerUtil.getFolderNames().get(i).getFolderName())) {
						return;
					}
				}


				// folderNames.get(i).getIsSelected();
				if (!TextUtils.isEmpty(fileManagerUtil.getFolderNames().get(i).getIsSelected())) {
					Intent keyBoardIntent = new Intent(ManagerActivity1.this, KeyboardActivity.class);
					// startActivity(keyBoardIntent);
					keyBoardIntent.putExtra("folderName", fileManagerUtil.getFolderNames().get(i).getFolderName());
					keyBoardIntent.putExtra("title", getText(R.string.folder_name));

					startActivityForResult(keyBoardIntent, 101);
				}

			}

		} else {
			allShengDialog = new AllShengDialog(ManagerActivity1.this, "", "需要选中一个文件夹，才能进行编辑！", "确定");
			allShengDialog.setClicklistener(new AllShengDialog.ClickListenerInterface() {

				@Override
				public void OK() {
					// TODO Auto-generated method stub
					allShengDialog.dismiss();
				}

				@Override
				public void Cancle() {
					// TODO Auto-generated method stub
					allShengDialog.dismiss();
				}

			});
			allShengDialog.show();
			// ByAlert.alert("需要选中一个文件夹，才能进行编辑！");
		}

	}

	@Override
	public void editFileFunction() {
		if (folderSelector) {
			Intent keyBoardIntent = new Intent(ManagerActivity1.this, KeyboardActivity.class);

			keyBoardIntent.putExtra("folderName", fileNameTV.getText());
			keyBoardIntent.putExtra("title", getText(R.string.file_name));
			startActivityForResult(keyBoardIntent, 102);
		} else {
			allShengDialog = new AllShengDialog(ManagerActivity1.this, "", "需要选中一个文件夹，才能进行编辑！", "确定");
			allShengDialog.setClicklistener(new AllShengDialog.ClickListenerInterface() {

				@Override
				public void OK() {
					// TODO Auto-generated method stub
					allShengDialog.dismiss();
				}

				@Override
				public void Cancle() {
					// TODO Auto-generated method stub
					allShengDialog.dismiss();
				}

			});
			allShengDialog.show();
			// ByAlert.alert("需要选中一个文件夹，才能进行编辑！");
		}

	}

	@Override
	public void addFolderFunction() {
		// 标记为改成否定颜色清空
		folderSelector = false;
		for (int i = 0; i < folderList.getCount() - 1; i++) {
			fileManagerUtil.getFolderNames().get(i).setIsSelected("");
		}
		folderAdapter.upData(fileManagerUtil.getFolderNames());
		folderAdapter.notifyDataSetChanged();
		Intent keyBoardIntent = new Intent(ManagerActivity1.this, KeyboardActivity.class);
		// keyBoardIntent.putExtra("folderName", folderNames
		// .get(i).getFileName());
		keyBoardIntent.putExtra("title", getText(R.string.add_a_new_folder));
		startActivityForResult(keyBoardIntent, 103);

	}

	// 设置actionBar
	public void setActionBar() {
		Button leftfirstBtn;
		TextView title;

		leftfirstBtn = BindView(R.id.leftfirst_btn);
		title = BindView(R.id.title);

		leftfirstBtn.setVisibility(View.VISIBLE);
		leftfirstBtn.setText(R.string.item_actionbar_home);
		title.setText(R.string.filemanagerActivity_title);

		leftfirstBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ManagerActivity1.this, MainMenuActivity.class);
				startActivity(intent);
				finish();
			}
		});

	}

	// 获取当前时间的方法
	public void setSystemTime() {

		TextView date, fileName;
		date = BindView(R.id.date);
		fileName = BindView(R.id.file_name);

		// 获取系统时间
		SimpleDateFormat sdfDate = new SimpleDateFormat("MM dd,yyyy");
		date.setText(sdfDate.format(new Date()));

		// // 文件路径置空
		// fileName.setText(SharedPreferencesUtils.get(this,
		// BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "") + "/"
		// + SharedPreferencesUtils.get(this,
		// BaseApplication.FILEMANGER_PREPAREFILENAME, ""));

	}

	// 设置bottom布局
	public void setBottomView() {

		bottomLeftFistBtn = BindView(R.id.bottomLeftFistBtn);
		bottomCenterBtn = BindView(R.id.bottomCenterBtn);
		bottomRightBtn = BindView(R.id.bottomRightBtn);

		bottomLeftFistBtn.setVisibility(View.VISIBLE);
		// bottomCenterBtn.setVisibility(View.VISIBLE);
		bottomRightBtn.setVisibility(View.VISIBLE);

		bottomLeftFistBtn.setText(R.string.bottomView_back);
		// TODO 这个button的文字不确定暂时用A代替
		bottomCenterBtn.setText("A"); // 不确定！！！！！！！
		bottomRightBtn.setText(R.string.bottomView_next);

		bottomLeftFistBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(ManagerActivity1.this, MainMenuActivity.class);
				startActivity(intent);
				finish();

			}
		});

		bottomCenterBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ByAlert.alert("A");

			}
		});
		bottomRightBtn.setVisibility(View.GONE);
		bottomRightBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// // 先判定是否选择文件的目录
				if (!folderSelector) {
					ByAlert.alert(getString(R.string.manager_sureafile));
					return;
				}

				if (stateTv.getText().toString().contains("new") || stateTv.getText().toString().contains("新建")) {
					// 先将本页面的存储的信息暂时保存到sp中

					for (int i = 0; i < folderList.getCount() - 1; i++) {
						// folderNames.get(i).getIsSelected();
						if (!TextUtils.isEmpty(fileManagerUtil.getFolderNames().get(i).getIsSelected())) {
							SharedPreferencesUtils.put(ManagerActivity1.this,
									BaseApplication.FILEMANGER_PREPAREFOLDERPATH,
									fileManagerUtil.getFolderNames().get(i).getFolderName());
						}

					}
					SharedPreferencesUtils.put(ManagerActivity1.this, BaseApplication.FILEMANGER_PREPAREFILENAME,
							fileNameTV.getText() + ".csv");
					if (!fileManagerUtil.fileExist(
							(String) SharedPreferencesUtils.get(ManagerActivity1.this,
									BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0"),
							(String) SharedPreferencesUtils.get(ManagerActivity1.this,
									BaseApplication.FILEMANGER_PREPAREFILENAME, "0"),
							ManagerActivity1.this)) {
						// final AllShengDialog allShengDialog = new
						// AllShengDialog(
						// BaseApplication.getContext(), "",
						// "此文件已经创建过，请更换文件名称", "OK");
						// allShengDialog
						// .setClicklistener(new ClickListenerInterface() {
						//
						// @Override
						// public void OK() {
						// // TODO Auto-generated method stub
						// allShengDialog.dismiss();
						// }
						//
						// });
						// allShengDialog.show();
						return;
					}

					allShengDialog = new AllShengDialog(ManagerActivity1.this, "",
							"你选择的文件路径是:"
									+ (String) SharedPreferencesUtils.get(ManagerActivity1.this,
											BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0")
									+ "\n你选择的文件名称是:" + (String) SharedPreferencesUtils.get(ManagerActivity1.this,
											BaseApplication.FILEMANGER_PREPAREFILENAME, "0"),
							"确定");
					allShengDialog.setClicklistener(new AllShengDialog.ClickListenerInterface() {

						@Override
						public void OK() {
							// TODO Auto-generated method stub
							Intent nextIntent = new Intent(ManagerActivity1.this, BaseInformationActivity.class);

							startActivity(nextIntent);
							allShengDialog.dismiss();
						}

						@Override
						public void Cancle() {
							// TODO Auto-generated method stub
							allShengDialog.dismiss();
						}

					});
					allShengDialog.show();
					// ByAlert.alert("你选择的文件路径是:"
					// + (String) SharedPreferencesUtils.get(
					// FileManagerActivity.this,
					// BaseApplication.FILEMANGER_PREPAREFOLDERPATH,
					// "0"));
					// ByAlert.alert("你选择的文件名称是:"
					// + (String) SharedPreferencesUtils
					// .get(FileManagerActivity.this,
					// BaseApplication.FILEMANGER_PREPAREFILENAME,
					// "0"));

				} else if (stateTv.getText().toString().contains("save as")
						|| stateTv.getText().toString().contains("另存为")) {

					// 先将本页面的存储的信息暂时保存到sp中

					for (int i = 0; i < folderList.getCount() - 1; i++) {
						// folderNames.get(i).getIsSelected();
						if (!TextUtils.isEmpty(fileManagerUtil.getFolderNames().get(i).getIsSelected())) {
							SharedPreferencesUtils.put(ManagerActivity1.this,
									BaseApplication.FILEMANGER_PREPAREFOLDERPATH,
									fileManagerUtil.getFolderNames().get(i).getFolderName());
						}

					}
					SharedPreferencesUtils.put(ManagerActivity1.this, BaseApplication.FILEMANGER_PREPAREFILENAME,
							fileNameTV.getText() + ".csv");
					if (!fileManagerUtil.fileExist(
							(String) SharedPreferencesUtils.get(ManagerActivity1.this,
									BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0"),
							(String) SharedPreferencesUtils.get(ManagerActivity1.this,
									BaseApplication.FILEMANGER_PREPAREFILENAME, "0"),
							ManagerActivity1.this)) {
						// final AllShengDialog allShengDialog = new
						// AllShengDialog(
						// BaseApplication.getContext(), "",
						// "此文件已经创建过，请更换文件名称", "OK");
						// allShengDialog
						// .setClicklistener(new ClickListenerInterface() {
						//
						// @Override
						// public void OK() {
						// // TODO Auto-generated method stub
						// allShengDialog.dismiss();
						// }
						//
						// });
						// allShengDialog.show();
						ByAlert.alert(getString(R.string.manager_fileexist));
						return;
					}
					StringBuffer contextString = new StringBuffer();
					for (FileBean bean : fileBeans2) {
						if (!TextUtils.isEmpty(bean.getIsSelected())) {
							folderName = bean.getFoldName();
							fileName = bean.getFileName();
						}
					}

					String path = appFilePath + "/" + folderName;

					File file = new File(path + "/" + fileName);
					contextString = new StringBuffer();
					BufferedReader reader = null;
					try {
						System.out.println("以行为单位读取文件内容，一次读一整行:");
						reader = new BufferedReader(new FileReader(file));
						String tempString = null;
						int line = 1;
						// 一次读入一行，直到读入null为文件结束
						while ((tempString = reader.readLine()) != null) {
							// 显示行号
							// System.out.println("line " + line + ": " +
							// tempString);
							// Log.e("--", tempString);
							contextString.append(tempString);
							contextString.append(",");
							line++;
						}
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (reader != null) {
							try {
								reader.close();

							} catch (IOException e1) {
							}
						}
					}
					LogUtil.e(contextString);
					if (!contextString.toString().contains("Aisle")) {
						ByAlert.alert(getString(R.string.ana_brow_layout1_));
						return;
					}
					if (!contextString.toString().contains("dataSourceListBlock1")
							| !contextString.toString().contains("dataSourceListBlock2")) {
						ByAlert.alert(getString(R.string.ana_brow_genepan));
						return;
					}
					if (!contextString.toString().contains("Methods")) {
						ByAlert.alert(getString(R.string.ana_brow_methods_));
						return;
					}
					// 有实验数据的只拿实验设置的数据就行了
					// if (contextString.toString().contains(",,Channel1")) {
					// // 在分析数据的时候应该将判断条件前面加非
					// ByAlert.alert("此文已经有运行数据！");
					// return;
					// }
					for (int i = 0; i < fileBeans2.size(); i++) {
						if (!TextUtils.isEmpty(fileBeans2.get(i).getIsSelected())) {
							fileBeans2.get(i).getFoldName();
							fileBeans2.get(i).getFileName();
							String fileFrom, fileTo;

							String appFilePath = Environment.getExternalStorageDirectory() + "/" + "AllShengMedical";
							fileFrom = appFilePath + "/" + fileBeans2.get(i).getFoldName() + "/"
									+ fileBeans2.get(i).getFileName();
							fileTo = appFilePath + "/"
									+ SharedPreferencesUtils.get(ManagerActivity1.this,
											BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "")
									+ "/" + SharedPreferencesUtils.get(ManagerActivity1.this,
											BaseApplication.FILEMANGER_PREPAREFILENAME, "");
							File file1 = new File(fileTo);
							try {
								file1.createNewFile();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							// CopyFile copyFile = new CopyFile();
							// copyFile.copy(fileFrom, fileTo);
							contextString = new StringBuffer();
							reader = null;
							try {
								System.out.println("以行为单位读取文件内容，一次读一整行:");
								reader = new BufferedReader(new FileReader(fileFrom));
								String tempString = null;
								int line = 1;
								// 一次读入一行，直到读入null为文件结束
								while ((tempString = reader.readLine()) != null) {
									// 显示行号
									// System.out.println("line " + line + ": "
									// +
									// tempString);
									// Log.e("--", tempString);

									// if (tempString.contains("Raw Data")) {
									// break;
									// } else {
									// if (line != 1) {
									// contextString.append("\r\n");
									// }
									// }
									if (tempString.contains("Raw Data")) {
										break;
									} else {
										if (line != 1) {
											contextString.append("\r\n");
										}
										contextString.append(tempString);
									}

									line++;
								}
								reader.close();
							} catch (IOException e) {
								e.printStackTrace();
							} finally {
								if (reader != null) {
									try {
										reader.close();

									} catch (IOException e1) {
									}
								}
							}
							String folderName = SharedPreferencesUtils.get(ManagerActivity1.this,
									BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
							String fileName = SharedPreferencesUtils.get(ManagerActivity1.this,
									BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";
							fileManagerUtil.createFIle(folderName, fileName);
							fileManagerUtil.writeFile(folderName, fileName, contextString + "", false);

							// history
							ArrayList<FileBean> fileBeans = new ArrayList<FileBean>();

							// 读取
							SharedPreferences preferences = getSharedPreferences(
									BaseApplication.FILEMANGER_HISTORYARRAYLIST, MODE_PRIVATE);
							String json = preferences.getString("fileBean", null);

							if (json != null) {
								Gson gson = new Gson();
								Type type = new TypeToken<List<FileBean>>() {
								}.getType();

								fileBeans = gson.fromJson(json, type);
								for (int j = 0; j < fileBeans.size(); j++) {
									Log.d("读sp", fileBeans.get(j).getFoldName() + ":" + fileBeans.get(j).getFileName()
											+ "," + fileBeans.get(j).getCreateTime());
								}
							}

							String chosenFilePath = Environment.getExternalStorageDirectory() + "/" + "AllShengMedical"
									+ "/" + folderName + "/" + fileName;

							File chosenFile = new File(chosenFilePath);
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							long time = chosenFile.lastModified();

							FileBean fileBean = new FileBean(fileName, format.format(new Date(time)), "", folderName);

							// 遍历现在加的文件历史有没有，如果有就不加，没有加如集合。
							// 还要判断文件集合 的size ，如果集合大于20就要删除最后一个。再添加
							boolean spFileBoo = false;
							for (FileBean filebean : fileBeans) {
								if (fileBean.getFileName().equals(filebean.getFileName())) {
									if (fileBean.getFoldName().equals(filebean.getFoldName())) {
										spFileBoo = true;
									} else {

									}
								} else {

								}
							}
							if (!spFileBoo) {
								if (fileBeans.size() == 20) {
									fileBeans.remove(19);
								}
								fileBeans.add(0, fileBean);
							}

							// SharedPreferencesUtils.get(BaseInformationActivity.this,
							// BaseApplication.FILEMANGER_HISTORYARRAYLIST, "");

							// 如果名字有相同的就不加进去

							// 写
							SharedPreferences.Editor editor = getSharedPreferences(
									BaseApplication.FILEMANGER_HISTORYARRAYLIST, MODE_PRIVATE).edit();
							Gson gson = new Gson();
							String json2 = gson.toJson(fileBeans);
							Log.d("gson写", "saved json is " + json2);
							editor.putString("fileBean", json2);
							editor.commit();

							SharedPreferences preferences1 = getSharedPreferences(
									BaseApplication.FILEMANGER_HISTORYARRAYLIST, MODE_PRIVATE);
							String json1 = preferences1.getString("fileBean", null);
							fileBeans2 = new ArrayList<FileBean>();
							if (json1 != null) {
								Gson gson1 = new Gson();
								Type type = new TypeToken<List<FileBean>>() {
								}.getType();

								fileBeans2 = gson1.fromJson(json1, type);
								for (int j = 0; j < fileBeans2.size(); j++) {
									Log.d("读sp", fileBeans2.get(j).getFoldName() + ":" + fileBeans2.get(j).getFileName()
											+ "," + fileBeans2.get(j).getCreateTime());
								}
							}
							fileAdapter.notifyDataSetChanged();

							allShengDialog = new AllShengDialog(ManagerActivity1.this, "",
									"你将要操作的文件是：" + folderName + "/" + fileName + "\n选择要复制的文件路径是:"
											+ (String) SharedPreferencesUtils.get(ManagerActivity1.this,
													BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0")
											+ "/" + (String) SharedPreferencesUtils.get(ManagerActivity1.this,
													BaseApplication.FILEMANGER_PREPAREFILENAME, "0"),
									"确定");

							allShengDialog.setClicklistener(new AllShengDialog.ClickListenerInterface() {

								@Override
								public void OK() {
									// TODO Auto-generated method stub
									Intent nextIntent = new Intent(ManagerActivity1.this,
											EditBaseInformationActivity.class);

									startActivity(nextIntent);
									allShengDialog.dismiss();
								}

								@Override
								public void Cancle() {
									// TODO Auto-generated method stub
									allShengDialog.dismiss();
								}

							});
							allShengDialog.show();
						}

					}
				}

			}
		});
	}

	// 配置文件夹的listView
	private void initFolderListView() {
		fileManagerUtil.getFolderInfo();
		for (FolderBean bean : fileManagerUtil.getFolderNames()) {
			if ("Default".equals(bean.getFolderName())) {
				bean.setIsSelected("1");
			}
		}

		fileManagerUtil.getFolderNames();

		ArrayList<FolderBean> folderNamesCopy = new ArrayList<FolderBean>();
		folderNamesCopy.addAll(fileManagerUtil.getFolderNames());
		int index = 0;
		for (int i = 0; i < fileManagerUtil.getFolderNames().size(); i++) {
			if ("Default".equals(fileManagerUtil.getFolderNames().get(i).getFolderName())) {
				index = i;
			}
		}
		fileManagerUtil.getFolderNames().clear();
		fileManagerUtil.getFolderNames().add(folderNamesCopy.get(index));
		folderNamesCopy.remove(index);
		fileManagerUtil.getFolderNames().addAll(folderNamesCopy);

		folderAdapter = new FolderAdapter(this, fileManagerUtil.getFolderNames());
		LayoutInflater infla = LayoutInflater.from(this);
		View footView = infla.inflate(R.layout.item_listview_folder_footview, null);
		folderList.addFooterView(footView);
		folderList.setAdapter(folderAdapter);

		footView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				fileManagerPresenter.addFolderFunction();
			}

		});

		folderList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// folderList.getCount();
				for (int i = 0; i < folderList.getCount() - 1; i++) {

					fileManagerUtil.getFolderNames().get(i).setIsSelected("");

				}

				// 判断是否在搜索

				fileManagerUtil.getFolderNames().get(position).setIsSelected("1");
				folderAdapter.upData(fileManagerUtil.getFolderNames());
				folderAdapter.notifyDataSetChanged();

				// // 查询文件夹下面有什么文件！
				// fileAdapter.clear();
				//
				// getFileInfo(fileManagerUtil.getFolderNames().get(position)
				// .getFolderName());
				// fileAdapter = new FileAdapter(BaseApplication.getContext(),
				// fileManagerUtil.getFileNames(), fileBean);
				// fileAdapter.notifyDataSetChanged();
				// LayoutInflater infla = LayoutInflater.from(BaseApplication
				// .getContext());
				// View footView = infla.inflate(
				// R.layout.item_listview_folder_footview, null);

				// fileList.setAdapter(fileAdapter);

				folderSelector = true;

			}

		});
	}

	// 文件夹的ListView适配器
	public class FolderAdapter extends BaseAdapter {
		private Context mContext;
		ArrayList<FolderBean> folderNames;

		private LayoutInflater inflater;
		boolean defaultShow = false;

		public FolderAdapter() {
			super();
		}

		public FolderAdapter(Context mContext, ArrayList<FolderBean> folderNames) {
			super();
			this.folderNames = folderNames;
			this.mContext = mContext;

			inflater = LayoutInflater.from(mContext);
		}

		public void upData(ArrayList<FolderBean> folderNames) {

			this.folderNames = folderNames;

		}

		class ViewHolder {

			TextView folderNameTv;
			LinearLayout line;

		}

		@Override
		public int getCount() {
			return folderNames != null ? folderNames.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			return folderNames != null ? folderNames.get(position) : null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;

			if (holder == null) {
				convertView = inflater.inflate(R.layout.item_listview_folder, null);
				holder = new ViewHolder();

				holder.folderNameTv = (TextView) convertView.findViewById(R.id.folderNameTv);

				holder.line = (LinearLayout) convertView.findViewById(R.id.line);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.folderNameTv.setText(folderNames.get(position).getFolderName());
			if ("1".equals(folderNames.get(position).getIsSelected())) {
				holder.line.setBackgroundColor(getResources().getColor(R.color.selected_color));
			} else {
				holder.line.setBackgroundColor(getResources().getColor(R.color.white));
			}

			return convertView;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 点击文件夹编辑，返回时传数据
		if (requestCode == 101 && resultCode == 201) {
			String result = data.getExtras().getString("result");
			String oldName = data.getExtras().getString("oldName");
			for (int i = 0; i < folderList.getCount() - 1; i++) {
				if (!TextUtils.isEmpty(fileManagerUtil.getFolderNames().get(i).getIsSelected())) {
					String appOldFilePath = Environment.getExternalStorageDirectory() + "/" + "AllShengMedical/"
							+ fileManagerUtil.getFolderNames().get(i).getFolderName();

					String appNewFilePath = Environment.getExternalStorageDirectory() + "/" + "AllShengMedical/"
							+ result;

					fileManagerUtil.updateFolderName(appOldFilePath, appNewFilePath);

					// 标记为改成否定颜色清空
					folderSelector = false;
					for (int j = 0; j < folderList.getCount() - 1; j++) {
						fileManagerUtil.getFolderNames().get(j).setIsSelected("");
					}

					fileManagerUtil.getFolderInfo();
					folderAdapter.upData(fileManagerUtil.getFolderNames());
					folderAdapter.notifyDataSetChanged();
				}
			}
			
			ArrayList<FileBean> fileBeans = new ArrayList<FileBean>();
			// 读取
			SharedPreferences preferences = getSharedPreferences(BaseApplication.FILEMANGER_HISTORYARRAYLIST,
					MODE_PRIVATE);
			String json = preferences.getString("fileBean", null);

			if (json != null) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<FileBean>>() {
				}.getType();

				fileBeans = gson.fromJson(json, type);
				for (int i = 0; i < fileBeans.size(); i++) {
					Log.d("读sp", fileBeans.get(i).getFoldName() + ":" + fileBeans.get(i).getFileName() + ","
							+ fileBeans.get(i).getCreateTime());
				}
			}
			
			
			for(int i =0 ;i <fileBeans.size();i++){
				if(oldName.equals(fileBeans.get(i).getFoldName())){
					fileBeans.get(i).setFoldName(result);
				}
			}
			fileBeans2=fileBeans;
			fileAdapter = new FileAdapter(ManagerActivity1.this, (ArrayList<FileBean>) fileBeans2);
			fileList.setAdapter(fileAdapter);
			// 写
			SharedPreferences.Editor editor = getSharedPreferences(BaseApplication.FILEMANGER_HISTORYARRAYLIST,
					MODE_PRIVATE).edit();
			Gson gson = new Gson();
			String json2 = gson.toJson(fileBeans);
			Log.d("gson写", "saved json is " + json2);
			editor.putString("fileBean", json2);
			editor.commit();
		}
		// 点击文件夹编辑，返回时传不数据
		if (requestCode == 101 && resultCode == 202) {

		}
		// 点击文件编辑，返回时传数据
		if (requestCode == 102 && resultCode == 201) {

			String result = data.getExtras().getString("result");// 得到新Activity

			fileNameTV.setText(result);

			// getFolderInfo();
			// fileBean.setFileName(result);
			// fileAdapter = new FileAdapter(BaseApplication.getContext(),
			// fileManagerUtil.getFileNames(), fileBean);
			// fileAdapter.notifyDatasetChanged
			// adapter.notifyDatasetInvalidate
			// listview.refreshAllViews;
			// fileList.removeAllViewsInLayout();
			// fileList.postInvalidate();
			// //
			// fileList.setAdapter(fileAdapter);
			// ByAlert.alert(fileBean.getFileName() + "!!!!");
			// fileAdapter.notifyDataSetChanged();

		}
		// 点击文件编辑，返回时传不数据
		if (requestCode == 102 && resultCode == 202) {
			// String result = data.getExtras().getString("result");//
			// 得到新Activity
			// 关闭后返回的数据
			// ByAlert.alert(result);
		}
		// 点击添加文件夹，返回传值成功
		if (requestCode == 103 && resultCode == 201) {

			String result = data.getExtras().getString("result");
			// 得到新Activity
			// 关闭后返回的数据
			fileManagerUtil.addFolder(result + "");
			folderAdapter.upData(fileManagerUtil.getFolderNames());
			folderAdapter.notifyDataSetChanged();

		}
		// 点击添加文件夹，返回传值失败
		if (requestCode == 103 && resultCode == 202) {

		}
		// // 点击搜索文件夹，返回传值成功
		// if (requestCode == 104 && resultCode == 201) {
		//
		// String result = data.getExtras().getString("result");
		// searchTv.setText(result);
		// fileManagerUtil.searchAndSort(result);
		// folderAdapter.upData(fileManagerUtil.getSearchFolderNames());
		// folderAdapter.notifyDataSetChanged();
		// }
		// // 点击搜索文件夹，返回传值失败
		// if (requestCode == 104 && resultCode == 202) {
		// fileManagerUtil.getFolderInfo();
		// }

	}

	// 文件的ListView适配器
	public class FileAdapter extends BaseAdapter {
		private Context mContext;
		private ArrayList<FileBean> fileNames;
		private LayoutInflater inflater;

		// private FileBean fileBean;

		public FileAdapter() {
			super();
		}

		public FileAdapter(Context mContext, ArrayList<FileBean> fileNames) {
			super();
			this.fileNames = fileNames;
			this.mContext = mContext;
			// this.fileBean = fileBean;
			inflater = LayoutInflater.from(mContext);
		}

		public void clear() {
			// this.fileBean = new FileBean();
			ArrayList<FileBean> collection = new ArrayList<FileBean>();
			this.fileNames = collection;
			notifyDataSetChanged();
		}

		class ViewHolder {

			TextView fileNameTv, createTimeTv, foldTv;
			LinearLayout line;

		}

		@Override
		public int getCount() {
			return fileNames != null ? fileNames.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			return fileNames.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (holder == null) {
				convertView = inflater.inflate(R.layout.item_listview_file1, null);
				holder = new ViewHolder();

				holder.fileNameTv = (TextView) convertView.findViewById(R.id.fileNameTv);
				holder.createTimeTv = (TextView) convertView.findViewById(R.id.createTimeTv);
				holder.line = (LinearLayout) convertView.findViewById(R.id.line);
				holder.foldTv = (TextView) convertView.findViewById(R.id.foldTv);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// if (position == 0) {
			// if (TextUtils.isEmpty(fileBean.getFileName())) {
			// StringBuffer fileName = new StringBuffer();
			// fileName.append("FileName");
			// SimpleDateFormat myFmt = new SimpleDateFormat(
			// "yyyy-MM-dd-HH-mm-ss");
			// fileName.append(myFmt.format(System.currentTimeMillis()));
			// fileBean.setFileName(fileName + "");
			// }
			//
			// holder.fileNameTv.setText(fileBean.getFileName() + "");
			// SimpleDateFormat myFmt2 = new SimpleDateFormat(
			// "yyyy-MM-dd HH:mm:ss");
			// holder.createTimeTv.setText(myFmt2.format(System
			// .currentTimeMillis()));
			// holder.line.setBackground(getResources().getDrawable(
			// R.color.selected_color));
			// } else {
			// holder.fileNameTv.setText(fileNames.get(position - 1)
			// .getFileName());
			// holder.createTimeTv.setText(fileNames.get(position - 1)
			// .getCreateTime());
			// }

			holder.fileNameTv.setText(fileNames.get(position).getFileName() + "");

			holder.foldTv.setText(fileNames.get(position).getFoldName());

			holder.createTimeTv.setText(fileNames.get(position).getCreateTime() + "");
			if (TextUtils.isEmpty(fileNames.get(position).getIsSelected())) {
				holder.line.setBackground(getResources().getDrawable(R.color.white));
			} else {
				holder.line.setBackground(getResources().getDrawable(R.color.selected_color));
			}

			return convertView;
		}
	}

}
